package org.jeecg.modules.fangkgl.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.fangkgl.entity.AgFangkgl;
import org.jeecg.modules.fangkgl.service.IAgFangkglService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.kaoqyggl.entity.AgKaoqyggl;
import org.jeecg.modules.shangt.entity.ShangtGroup;
import org.jeecg.modules.shangt.entity.ShangtRtn;
import org.jeecg.modules.shangt.entity.ShangtUser;
import org.jeecg.modules.shangt.service.ShangTApiHelper;
import org.jeecg.modules.tongxjl.entity.AgTongxjl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 访客管理
 * @Author: jeecg-boot
 * @Date: 2020-10-22
 * @Version: V1.0
 */
@Api(tags = "访客管理")
@RestController
@RequestMapping("/fangkgl/agFangkgl")
@Slf4j
public class AgFangkglController extends JeecgController<AgFangkgl, IAgFangkglService> {
    @Autowired
    private IAgFangkglService agFangkglService;

    @Autowired
    ShangTApiHelper shangTApiHelper;

    @GetMapping(value = "/employeeList")
    public Result<?> employeeList(String type) {
        List<ShangtUser> list = shangTApiHelper.getEmployeeList(type);
        return Result.ok(list);
    }

    @GetMapping(value = "/groupList")
    public Result<?> groupList(String type) {
        List<ShangtGroup> list = shangTApiHelper.getEmployeeGroupList(type);
        return Result.ok(list);
    }

    @GetMapping(value = "/delete4Visitor")
    public Result<?> delete4Visitor(String id) {
        ShangtRtn rtn = shangTApiHelper.deleteVisitor(id);

        if (rtn.getMessage().equals("OK"))
            return Result.ok("删除成功！");
        else
            return Result.error(rtn.getDesc());
    }

    /**
     * 分页列表查询
     *
     * @param agFangkgl
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "访客管理-分页列表查询")
    @ApiOperation(value = "访客管理-分页列表查询", notes = "访客管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AgFangkgl agFangkgl,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) throws Exception {

        List<ShangtUser> list = shangTApiHelper.getEmployeeList("2");
        IPage<AgFangkgl> pageList = new Page<AgFangkgl>(pageNo, pageSize);

        List<AgFangkgl> list2 = new ArrayList<>();
        for (ShangtUser shangtUser : list
        ) {
            AgFangkgl agKaoqyggl1 = new AgFangkgl();
            agKaoqyggl1.setId(shangtUser.getId() + "");
            agKaoqyggl1.setShibzp(shangTApiHelper.picturePrefix + shangtUser.getAvatar());
            agKaoqyggl1.setXingm(shangtUser.getName());
            agKaoqyggl1.setMobile(shangtUser.getMobile());
//			agKaoqyggl1.setLaifmd(shangtUser.get)
            agKaoqyggl1.setYouxqks(DateUtils.parseDate(shangtUser.getDateTimeFrom(), "yyyy-MM-dd HH:mm:ss"));
            agKaoqyggl1.setYouxqjs(DateUtils.parseDate(shangtUser.getDateTimeTo(), "yyyy-MM-dd HH:mm:ss"));
            agKaoqyggl1.setLaifmd(shangtUser.getGuestPurpose());
            agKaoqyggl1.setJiedr(shangtUser.getReception_user_id() + "");
            agKaoqyggl1.setCreateTime(DateUtils.parseDate(shangtUser.getCreate_at(), "yyyy-MM-dd HH:mm:ss"));

            ShangtGroup shangtGroup = null;
            if (shangtUser.getGroupList() != null && shangtUser.getGroupList().size() > 0) {
                shangtGroup = shangtUser.getGroupList().get(0);
                agKaoqyggl1.setFangkz(shangtGroup.getName());
                agKaoqyggl1.setFangkzId(shangtGroup.getId() + "");
            }

            list2.add(agKaoqyggl1);
        }

        List listSorted = list2.stream().sorted(Comparator.comparing(AgFangkgl::getCreateTime).reversed()).collect(Collectors.toList());
        pageList.setRecords(listSorted);
        return Result.ok(pageList);
    }

    void writeToLocal(String destination, InputStream input) throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }

    /**
     * 添加
     *
     * @param agFangkgl
     * @return
     */
    @AutoLog(value = "访客管理-添加")
    @ApiOperation(value = "访客管理-添加", notes = "访客管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AgFangkgl agFangkgl) {
//		agFangkglService.save(agFangkgl);

        ShangtUser shangtUser = new ShangtUser();
        shangtUser.setName(agFangkgl.getXingm());
        shangtUser.setMobile(agFangkgl.getMobile());
        shangtUser.setGroups(agFangkgl.getFangkz());
        shangtUser.setGender(1);
        shangtUser.setGuestPurpose(agFangkgl.getLaifmd());
        shangtUser.setDateTimeFrom(DateUtils.formatDate(agFangkgl.getYouxqks(), "yyyy-MM-dd HH:mm:ss"));
        shangtUser.setDateTimeTo(DateUtils.formatDate(agFangkgl.getYouxqjs(), "yyyy-MM-dd HH:mm:ss"));
//        shangtUser.setReceptionUserId(Long.parseLong(agFangkgl.getJiedr()));
        shangtUser.setReceptionUserId(5790L);

        String tmpdir = System.getProperty("java.io.tmpdir");
        String toux = tmpdir + "toux.jpg";
        String shibzp = agFangkgl.getShibzp();
        String shibzp2 = "/temp" + shibzp.substring(shibzp.lastIndexOf("/"));
        InputStream is = MinioUtil.getMinioFile("anguan", shibzp2);

        ShangtRtn rtn = null;
        if (is != null) {
            try {
                writeToLocal(toux, is);

            } catch (IOException e) {
                e.printStackTrace();
            }
            rtn = shangTApiHelper.createVisitor(shangtUser, toux);

        } else
            rtn = shangTApiHelper.createVisitor(shangtUser, null);

        if (rtn.getMessage().equals("OK"))
            return Result.ok("添加成功！");
        else
            return Result.error(rtn.getMessage() + ", " + rtn.getDesc());
    }

    /**
     * 编辑
     *
     * @param agFangkgl
     * @return
     */
    @AutoLog(value = "访客管理-编辑")
    @ApiOperation(value = "访客管理-编辑", notes = "访客管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AgFangkgl agFangkgl) {
//		agFangkglService.updateById(agFangkgl);

        ShangtUser shangtUser = new ShangtUser();
        shangtUser.setId(Long.parseLong(agFangkgl.getId()));
        shangtUser.setName(agFangkgl.getXingm());
        shangtUser.setMobile(agFangkgl.getMobile());
        shangtUser.setGroups(agFangkgl.getFangkz());
        shangtUser.setGender(1);
        shangtUser.setGuestPurpose(agFangkgl.getLaifmd());
        shangtUser.setDateTimeFrom(DateUtils.formatDate(agFangkgl.getYouxqks(), "yyyy-MM-dd HH:mm:ss"));
        shangtUser.setDateTimeTo(DateUtils.formatDate(agFangkgl.getYouxqjs(), "yyyy-MM-dd HH:mm:ss"));
        shangtUser.setReceptionUserId(Long.parseLong(agFangkgl.getJiedr()));

        String tmpdir = System.getProperty("java.io.tmpdir");
        String toux = tmpdir + "toux.jpg";
        String shibzp = agFangkgl.getShibzp();
        String shibzp2 = "/temp" + shibzp.substring(shibzp.lastIndexOf("/"));
        InputStream is = MinioUtil.getMinioFile("anguan", shibzp2);

        ShangtRtn rtn = null;
        if (is != null) {
            try {
                writeToLocal(toux, is);

            } catch (IOException e) {
                e.printStackTrace();
            }
            rtn = shangTApiHelper.editVisitor(shangtUser, toux);

        } else
            rtn = shangTApiHelper.editVisitor(shangtUser, null);

        if (rtn.getMessage().equals("OK"))
            return Result.ok("添加成功！");
        else
            return Result.error(rtn.getMessage() + ", " + rtn.getDesc());
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "访客管理-通过id删除")
    @ApiOperation(value = "访客管理-通过id删除", notes = "访客管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        agFangkglService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "访客管理-批量删除")
    @ApiOperation(value = "访客管理-批量删除", notes = "访客管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.agFangkglService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "访客管理-通过id查询")
    @ApiOperation(value = "访客管理-通过id查询", notes = "访客管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AgFangkgl agFangkgl = agFangkglService.getById(id);
        if (agFangkgl == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(agFangkgl);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param agFangkgl
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AgFangkgl agFangkgl) {
        return super.exportXls(request, agFangkgl, AgFangkgl.class, "访客管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AgFangkgl.class);
    }

}
